import React from "react";
import { connect } from "dva";
import classnames from "classnames";
import { Form, Input } from "antd";
import { localUrl } from "../../utils/index";
// import { guid } from "../../utils/Date";
import img from "../../assets/head.png";
import "./Audio.less";

const FormItem = Form.Item;
const { TextArea } = Input;

@connect(({ add }) => ({
  add: add
}))
@Form.create({})
class AddAudio extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      videoError: false,
      imgError: false,
      loadingVideo: false,
      VideoUrl: "",
      imageUrl: img,
      percentVideo: 0,
      percentImage: 0,
      currentHive: "",
      marginLeft: 0,
      marginRight: 0
    };
  }

  componentDidMount() {
    // this.bar.show();
  }

  close = key => {
    this.props.dispatch({
      type: "add/close",
      key: key
    });
  };
  /**
   * 上传插件
   */
  fcUpload = key => {
    window.fc = null;
    let type;
    if (key === "video_src") {
      type = "video";
    } else if (key === "video_img") {
      type = "img";
    } else if (key === "audio_src") {
      type = "audio";
    }
    window.fc = new window.FcUpload({
      elem: "fcUpload" + type,
      multiple: false, //是否允许上传多个文件
      type: type, // 上传文件类型\ img 图片，  video 视频
      actionImg: `${localUrl}/fcpublic/uploads/uploadImg`, //本地上传图片地址
      actionVideo: `${localUrl}/fcpublic/uploads/uploadVideo`, //本地上传视频地址
      callback: callRes => {
        let url;
        // if (callRes.oss) {
        // oss 和本地返回数据结构不一样
        url = callRes.response[0];
        // } else {
        //   if (key == "video_src") {
        //     url = callRes.response[0].data.video_path;
        //   } else if (key == "video_img") {
        //     url = callRes.response[0].data;
        //   } else if (key == "audio_src") {
        //     url = callRes.response[0].data.video_path;
        //   }
        // }
        let obj = {};
        obj[key] = url;
        this.props.form.setFieldsValue(obj);
        // let storeAs = guid();
        // let nowDate = new Date();
        // let year = nowDate.getFullYear();
        // let month = nowDate.getMonth() + 1;
        // let day = nowDate.getDate();
        // let new_url = "transcode/" + year + "/" + month + "/" + day + "/" + storeAs;
        // let http = document.location.protocol + "//" + this.props.add.configJson.bucket + "." + this.props.add.configJson.endpoint + "/";
        // let old_url = url.replace(http, "");
        if (type === "audio") {
          this.props.dispatch({
            type: "add/setFields",
            data: {
              is_update: 1 //音频是否重新上传
            }
          });
        }
      }
    });

    window.fc.show();
  };
  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue();
    let about = [];
    this.props.add.gltjData.forEach((item, index) => {
      about.push(item.information_id);
    });
    data["about"] = about.join();
    data["img_arr"] = this.state.imgList;
    data["type"] = 2;
    return data;
  };
  getFieldsValue = () => {
    let data = this.props.form.getFieldsValue();
    this.props.form.validateFields();
    let validateArr = this.props.form.getFieldsError();
    let isDown = true;
    for (const key in validateArr) {
      if (validateArr.hasOwnProperty(key)) {
        //判断是否有效验错误
        if (validateArr[key]) {
          isDown = false;
          return;
        }
      }
    }
    if (isDown) {
      let about = [];
      this.props.add.gltjData.forEach((item, index) => {
        about.push(item.information_id);
      });
      data["about"] = about.join();
      data["img_arr"] = this.state.imgList;
      data["type"] = 2;
      return data;
    }
  };
  /**
   * 设置值
   */
  setFields = data => {
    // let formData = this.props.form.getFieldsValue();
    // if (formData.information_title) {
    //     data.information_title = formData.information_title;
    // }
    let setData = {};
    setData.video_title = data.title;
    setData.receive_site = data.push_site;
    setData.video_intro = data.summary;
    setData.audio_src = data.url;
    setData.key_word = data.keyword;
    setData.external_links = data.external_links || "";
    this.props.form.setFieldsValue(setData);
  };
  render() {
    // const imageUrl = this.props.form.getFieldValue("video_img");
    const VideoUrl = this.props.form.getFieldValue("audio_src");
    const {
      form: { getFieldDecorator }
    } = this.props;
    let video_title = this.props.form.getFieldValue("video_title");

    video_title = video_title ? video_title : "";

    let video_intro = this.props.form.getFieldValue("video_intro");

    video_intro = video_intro ? video_intro : "";

    const titleSuffix = <span className={classnames("titleLength", { red: video_title.length > 60 })}>{video_title.length}/60</span>;

    const introSuffix = <span className={classnames("introtitleLength", { red: video_intro.length > 2000 })}>{video_intro.length}/2000</span>;

    let key_word = this.props.form.getFieldValue("key_word");
    key_word = key_word ? key_word : "";

    const keyWordSuffix = <span className={classnames("titleLength", { red: key_word.length > 50 })}>{key_word.length}/50</span>;
    this.props.onRef(this);
    return (
      <div className="Video">
        <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
          {getFieldDecorator("video_title")(<Input prefix={<span className="red">*</span>} suffix={titleSuffix} className="subject" placeholder="请输入标题" maxLength={60} />)}
          {getFieldDecorator("key_word")(<Input className="subject keyword" suffix={keyWordSuffix} placeholder="请输入关键字" maxLength={50} />)}
          <div className="upload">
            <div className="video-box">
              <div className="title">
                音频上传<span className="red">（格式mp3，建议小于20M）</span>
              </div>
              {getFieldDecorator("audio_src")(
                <audio
                  onClick={() => {
                    this.fcUpload("audio_src");
                  }}
                  id="audio_src"
                  className="video_pic audio_src"
                  src={VideoUrl}
                  controls="controls"
                >
                  您的浏览器不支持 audio 标签。
                </audio>
              )}
            </div>
            {/* <div className="image">
              <div className="title">
                封面上传<span className="red">（建议尺寸比例16：9，小于2M）</span>
              </div>
              {getFieldDecorator("video_img", {
                initialValue: `${UrlConfig}/application/fcpublic/resource/images/default.png`
              })(
                <img
                  onClick={() => {
                    this.fcUpload("video_img");
                  }}
                  src={imageUrl}
                  className="video_pic"
                  alt="封面图"
                />
              )}
            </div> */}
          </div>
          <FormItem>
            {getFieldDecorator("video_intro")(<TextArea placeholder="请输入摘要" autosize={{ minRows: 2, maxRows: 6 }} className="subject" maxLength={2000} />)}
            {introSuffix}
          </FormItem>
          <FormItem
            label={
              <span className="title">
                外部链接<span className="hs">（选填）</span>
              </span>
            }
          >
            {getFieldDecorator("external_links")(<Input placeholder="外部链接" />)}
          </FormItem>
        </Form>
      </div>
    );
  }
}
export default AddAudio;
